package com.assistant.tasks.thread;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.assistant.common.Constants;
import com.assistant.common.utils.HttpClient;
import com.assistant.common.utils.uuid.Seq;
import com.assistant.tasks.mapper.TasksMapper;
import com.assistant.tasks.pojo.TaskDTO;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname AnalysisThread
 * @Description 异步任务线程类，用于处理文件分析任务
 * @Date 2025/3/5 17:38
 * @Created by xxx
 */
@Slf4j
@Data
@NoArgsConstructor
@EnableAsync
public class AnalysisThread implements Runnable {
    private TaskDTO taskDTO;
    private String fileDir0;
    private TasksMapper tasksMapper;

    public AnalysisThread(TaskDTO taskDTO, String fileDir0, TasksMapper tasksMapper) {
        this.taskDTO = taskDTO;
        this.fileDir0 = fileDir0;
        this.tasksMapper = tasksMapper;
    }

    @Override
    public void run() {
        // 执行文件分析任务
        File file = null;
        try {
            file = getFile();
        } catch (IOException e) {
            taskDTO.setState(Constants.STATE_FAIL);
            taskDTO.setStateTime(LocalDateTime.now());
            taskDTO.setMsg("文件上传失败");
            tasksMapper.update(taskDTO);
            return;
        }
        Map<String, File> fileParams = new HashMap<>();
        fileParams.put("file", file);
        String fileId = Seq.generate();
        Map<String, String> formParams = new HashMap<>();
        formParams.put("fileId", fileId);
        String result = null;
        try {
            result = HttpClient.doPostWithFiles(Constants.UA_URL, formParams, fileParams);
        } catch (IOException e) {
            taskDTO.setState(Constants.STATE_FAIL);
            taskDTO.setStateTime(LocalDateTime.now());
            taskDTO.setMsg(e.getMessage());
            tasksMapper.update(taskDTO);
            return;
        }
        JSONObject resultBody = JSON.parseObject(result);
        Object resultCode = resultBody.getString("code");
        if (!"0".equals(resultCode)) {
            taskDTO.setState(Constants.STATE_FAIL);
            taskDTO.setStateTime(LocalDateTime.now());
            taskDTO.setMsg(resultBody.getString("message"));
            tasksMapper.update(taskDTO);
            return;
        }
        JSONObject data = resultBody.getJSONObject("data");
        String pathURL = data.getString("pathURL");
        Path path = Paths.get(fileDir0, taskDTO.getDate() + Constants.CSV);
        String savePath = path.toString();
        try {
            HttpClient.downloadFile(pathURL, savePath);
        } catch (IOException e) {
            taskDTO.setState(Constants.STATE_FAIL);
            taskDTO.setStateTime(LocalDateTime.now());
            taskDTO.setMsg(e.getMessage());
            tasksMapper.update(taskDTO);
            return;
        }
        taskDTO.setFilePath(savePath);
        taskDTO.setState(Constants.STATE_SUCCESS);
        taskDTO.setStateTime(LocalDateTime.now());
        tasksMapper.update(taskDTO);
    }

    @Async
    protected File getFile() throws IOException {
        // 获取要分析的文件
        File file;
        if (taskDTO.getLocalFile() == null) {
            String fileName = taskDTO.getDate() + Constants.ZIP;
            Path filePath = Paths.get(fileDir0, fileName);
            Files.createDirectories(filePath.getParent());
            file = filePath.toFile();
            FileUtils.copyInputStreamToFile(taskDTO.getInputStream(), file);
            log.info("文件上传成功，文件名：{}", fileName);
            taskDTO.getInputStream().close();
        } else {
            file = taskDTO.getLocalFile();
        }
        return file;
    }
}
